const puppeteer = require("puppeteer");
let WSE_LIST = []; //存储browserWSEndpoint列表
let BROWSER_LIST = []; //存储browserWSEndpoint列表
const MAX_WSE = 4;

//负载均衡
const createWSEList = async () => {
    for (let i = 0; i < MAX_WSE; i++) {
        const browser = await puppeteer.launch({
            headless: "shell",
            //参数
            args: [
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--disable-setuid-sandbox',
                // '--no-first-run',
                '--no-sandbox',
                '--no-zygote',
                '--single-process'
            ],
            //一般不需要配置这条，除非启动一直报错找不到谷歌浏览器
            //executablePath:'chrome.exe在你本机上的路径，例如C:/Program Files/Google/chrome.exe'
        });
        let browserWSEndpoint = await browser.wsEndpoint();
        BROWSER_LIST.push(browser);
        WSE_LIST.push(browserWSEndpoint);
    }
}

const resetWSEList = () => {
    try {
        BROWSER_LIST.forEach(async browser => {
            await browser?.close()
        })
        WSE_LIST = []
        BROWSER_LIST = []
    } catch (error) {
        WSE_LIST = []
        BROWSER_LIST = []
    }

}

const fetchWSEList = () => WSE_LIST

module.exports = {
    createWSEList,
    resetWSEList,
    fetchWSEList
}
